package com.shanghaionstar.smart.presenter;

import android.content.Intent;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.smart.GetSmartDeviceResponse;
import com.onstar.cn.smart.SmartDevicesResponse;
import com.onstar.cn.smart.entity.GeoFencingEntity;
import com.onstar.cn.smart.request.BatchGeofencingReq;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.NavChooseInMapActivity;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.smart.SmartHomeActivity;
import com.shanghaionstar.smart.SmartSelDistanceFrg;
import com.shanghaionstar.smart.iview.ISmartTriggerView;
import com.shanghaionstar.smart.service.SmartHomeService;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.functions.Action1;

/**
 * Created by 7828wc on 2016/6/22.
 */
public class SmartTriggerPresenter extends BasePresenter<Object> {
    private BaseActivity mContext;
    private ISmartTriggerView mSmartTriggerView;
    private SmartHomeService service;
    private List<GetSmartDeviceResponse> mSmartDevices = new ArrayList<>();
    private SmartDevicesResponse mSmartDevicesRes;
    private UserAddressInfoImpl userAddressInfoImpl;

    public SmartTriggerPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<Object> view) {
        super.setView(view);
        mSmartTriggerView = (ISmartTriggerView) view;
        mContext = (BaseActivity) mSmartTriggerView.onActivity();
        service = new SmartHomeService(mContext);
        if (userAddressInfoImpl == null) {
            userAddressInfoImpl = new UserAddressInfoImpl(mContext);
        }
    }

    public void setAddress() {
        PoiItemInfo mPoiItemInfo = userAddressInfoImpl.quaryUserAddressInfo("1");
        setAddressTxt(mPoiItemInfo);
    }

    public void saveHomeAddress( PoiItemInfo poiItemInfo) {
        userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "1");
    }


    private void setAddressTxt(PoiItemInfo mPoiItemInfo) {
        if (mPoiItemInfo != null && mPoiItemInfo.getTitle() != null)
            mSmartTriggerView.setHomeAddress(mPoiItemInfo.getTitle());
    }

    public void getSmartDevices() {
        subscription = service.getSmartDevices().subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<SmartDevicesResponse>() {
                    @Override
                    public void call(SmartDevicesResponse mSmartDevicesRes) {
                        mSmartTriggerView.setLoading(false);
                        SmartTriggerPresenter.this.mSmartDevicesRes = mSmartDevicesRes;
                        mSmartDevices = mSmartDevicesRes.devices;
                        if (mSmartDevices != null && !mSmartDevices.isEmpty()) {
                            mSmartTriggerView.initData(mSmartDevices);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartTriggerView.setLoading(false);
                        if (throwable != null)
                            mSmartTriggerView.onResponseError((OnStarException) throwable);
                    }
                });
    }

    public void batchSmartGeoFencing(HashSet<Object> values) {
        mSmartTriggerView.setLoading(true);
        List<GeoFencingEntity> geoEntitys = mSmartDevicesRes.geofencings;
        BatchGeofencingReq req = setUpBatchReq(geoEntitys, values);
        RequestEntity entity = NetConnectUtil.getAuthRequestEntity(mContext);
        entity.setBody(new Gson().toJson(req));
        subscription = service.batchSmartGeoFencing(entity).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<GeoFencingEntity>() {
                    @Override
                    public void call(GeoFencingEntity fencingEntity) {
                        mSmartTriggerView.setLoading(false);
                        if (fencingEntity != null && !TextUtils.isEmpty(fencingEntity.geoFencingID)) {
                            new ToastView(mContext).showToast(mContext.getString(R.string.smart_geo_success));
                            if (!TextUtils.isEmpty(fencingEntity.range))
                                mSmartDevicesRes.geofencings.add(fencingEntity);
                            mSmartTriggerView.onReponseSuccess(fencingEntity);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartTriggerView.setLoading(false);
                        if (throwable != null)
                            mSmartTriggerView.onResponseError((OnStarException) throwable);
                    }
                });
    }

    public void goToSetAddress() {
//        Intent intent = new Intent(mapActivity, NavChooseInMapActivity.class);
////                startActivityForResult(intent,1);
        Intent it = new Intent(mContext,NavChooseInMapActivity.class);
        it.putExtra("mapChoosePoiType",MapChoosePoiType.SMART);
//        it.putExtra(MapChoosePoiType.SMART.name(),MapChoosePoiType.SMART.toString());
        mContext.startActivityForResult(it,1);
//        it.putExtra(MapChoosePoiType.SMART.name(),MapChoosePoiType.SMART.toString());
//        mContext.startActivity(it);
//        NavSetAddressFragment navSetAddressFragment = NavSetAddressFragment.newInstance(MapChoosePoiType.SMART);
////       mContext.changeFragment(mContext.getSupportFragmentManager(), navSetAddressFragment, NavSetAddressFragment.class, true);
//        NavChoosePointInMapFragment navChoosePointInMapFragment = NavChoosePointInMapFragment.newInstance(MapChoosePoiType.SMART);
//        mContext.addFragment(mContext.getSupportFragmentManager(), navChoosePointInMapFragment, true);
//        mContext.addFragment(mContext.getSupportFragmentManager(), navSetAddressFragment, true);
//        mContext.showFragment(mContext.getSupportFragmentManager(), NavSetAddressFragment.class, SmartTriggerFrg.class);
    }

    private BatchGeofencingReq setUpBatchReq(List<GeoFencingEntity> geoEntitys, HashSet<Object> values) {
        BatchGeofencingReq req = new BatchGeofencingReq();
        try {
            String distance = ((SmartHomeActivity) mContext).distance;
            int range = Integer.parseInt(getNumbers(distance));
            String geoFencingId = "";
            if (geoEntitys != null && !geoEntitys.isEmpty()) {
                for (GeoFencingEntity entity : geoEntitys) {
                    String _range = entity.range.substring(0, entity.range.lastIndexOf("."));
                    if (_range.equalsIgnoreCase(range + "")) {
                        geoFencingId = entity.geoFencingID;
                        break;
                    }
                }
                if (!TextUtils.isEmpty(geoFencingId)) {
                    req.geoFencingID = geoFencingId;
                } else {
                    setRange(req, distance, range);
                }
            } else {
                setRange(req, distance, range);
            }
            List<String> deviceIds = new ArrayList<String>();
            for (Object value : values) {
                int pos = Integer.parseInt(String.valueOf(value));
                GetSmartDeviceResponse response = mSmartDevices.get(pos);
                deviceIds.add(response.deviceId);
            }
            req.deviceIds = deviceIds;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return req;
    }

    private void setRange(BatchGeofencingReq req, String distance, int range) {
        req.range = range + "";
        String _range = req.range + "";
        req.rangeUnit = distance.substring(_range.length()).toUpperCase();
    }


    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    private void goToNavSearchActivity() {
//        Intent it = new Intent(mActivity, NavSearchActivity.class);
//        it.putExtra("FragmentFlag", Constans.TRIGGER);
//        mActivity.startActivityForResult(it, TRIGGER_REQUEST_CODE);
    }

    public void switchToSelDistanceFrg() {
        SmartSelDistanceFrg selDistanceFrg = new SmartSelDistanceFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), selDistanceFrg, SmartSelDistanceFrg.class, true);
    }


}



